package com.llkj.qingnianguoxue.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jm.chat.database.UserEntry;
import com.jm.chat.utils.SharePreferenceManager;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;

import java.io.File;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.DeviceInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

import static cn.jpush.im.android.api.jmrtc.JMRTCInternalUse.getApplicationContext;
import static com.llkj.qingnianguoxue.base.ConstantUserInfo.HUANXIN_PWD;

/**
 * Created by thinkpad on 2018/8/27.
 */

public class JGuangUtil {

    /**
     * 即时通讯登录
     */
    public static void loginHuanXin(String loginId,final String userName) {
        if (StringUtils.isEmpty(loginId)) {
            return;
        }
        /**=================     调用SDk登陆接口    =================*/
        JMessageClient.login(loginId, HUANXIN_PWD, new RequestCallback<List<DeviceInfo>>() {
            @Override
            public void gotResult(int responseCode, String responseMessage, List<DeviceInfo> result) {
                if (responseCode == 0) {
                    Log.e("MainActivity", "JMessageClient.login" + ", responseCode = " + responseCode + " ; LoginDesc = " + responseMessage);
                    UserInfo myInfo = JMessageClient.getMyInfo();
                    File avatarFile = myInfo.getAvatarFile();
                    //登陆成功,如果用户有头像就把头像存起来,没有就设置null
                    if (avatarFile != null) {
                        SharePreferenceManager.setCachedAvatarPath(avatarFile.getAbsolutePath());
                    } else {
                        SharePreferenceManager.setCachedAvatarPath(null);
                    }
                    String username = myInfo.getUserName();
                    String appKey = myInfo.getAppKey();
                    UserEntry user = UserEntry.getUser(username, appKey);
                    if (null == user) {
                        user = new UserEntry(username, appKey);
                        user.save();
                    }

                    updateNickName(userName);
                    updateHeadUrl();
                } else {
                    Log.e("MainActivity", "JMessageClient.login" + ", responseCode = " + responseCode + " ; LoginDesc = " + responseMessage);
                }
            }
        });
    }

    /**
     * 更新用户头像
     */
    private static void updateHeadUrl(){
        final String headUrl = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_HEAD);
        if(!StringUtils.isEmpty(headUrl)){

                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        try {
                            File file = Glide.with(MyApplication.getInstance())
                                    .load(headUrl)
                                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                    .get();
                            JGuangUtil.updateUserAvatar(file);
                        }catch (Exception e){
                            Log.e("Log","====="+e.getMessage());
                        }
                    }
                }.start();
        }

    }
    /**
     * 更新聊天昵称
     * @param nickName
     */
    public static void updateNickName(String nickName){
        try {
            JMessageClient.getMyInfo().setNickname(nickName);
            UserInfo mMyInfo = JMessageClient.getMyInfo();
            mMyInfo.setNickname(nickName);
            JMessageClient.updateMyInfo(UserInfo.Field.nickname, mMyInfo, new BasicCallback() {
                @Override
                public void gotResult(int responseCode, String responseMessage) {
                    if (responseCode == 0) {
                        //成功
                        Log.e("Log","===聊天昵称更新成功===");
                    } else {
                        Log.e("Log","===聊天昵称更新失败===");
                    }
                }
            });
        }catch (Exception e){
            Log.e("Log","=="+e.getMessage());
        }
    }

    /**
     * 更新用户头像
     * @param userAvatar
     */
    public static void updateUserAvatar(File userAvatar){
        try {
            JMessageClient.updateUserAvatar(userAvatar, new BasicCallback() {
                @Override
                public void gotResult(int responseCode, String responseMessage) {
                    if (responseCode == 0) {
                        Log.e("Log","===聊天头像更新成功===");
                        //成功
                    } else {
                        Log.e("Log","===聊天头像更新失败==="+responseCode+responseMessage);
                    }
                }
            });
        }catch (Exception e){
            Log.e("Log","=="+e.getMessage());
        }
    }

    /**
     * 首页接口调用，需要判断当前用户没有被其它设备登录
     */
    public void setJPushAlias(String alias){
        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("Log", logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("Log", logs);
                    if (isNetworkConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, tags), 1000 * 60);
                    } else {
                        Log.i("Log", "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("Log", logs);
            }

        }

    };

    private static final int MSG_SET_ALIAS = 1001;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.e("Log", "Set alias in handler.");
                    JPushInterface.setAliasAndTags(MyApplication.getInstance(), (String) msg.obj, null, mAliasCallback);
                    break;

                default:
                    Log.e("Log", "Unhandled msg - " + msg.what);
            }
        }
    };

    /**
     * 判断当前是否有网络
     *
     * @author lvliuyan
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
}
